package com.thinkit.cms.directives.method;

import cn.hutool.core.util.StrUtil;
import com.thinkit.directive.emums.LangEnum;
import com.thinkit.directive.emums.MethodEnum;
import com.thinkit.directive.render.BaseMethod;
import com.thinkit.utils.utils.Checker;
import freemarker.template.TemplateModelException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SubString extends BaseMethod {
    @Override
    public MethodEnum getName() {
        return MethodEnum.SUB;
    }

    @Override
    public Object exec(List list) throws TemplateModelException {
        String str = getString(0,list, LangEnum.STRING);
        Integer toIndex = getInteger(1,list, LangEnum.INTEGER);
        if(Checker.BeNull(toIndex)) toIndex =10;
        if(Checker.BeNotBlank(str)){
            String suffix = getString(2,list, LangEnum.STRING);
            String resStr = StrUtil.sub(str, 0, Checker.BeNotNull(toIndex)?toIndex:1);
            if(str.length()>toIndex.intValue()){
                if(Checker.BeNotBlank(suffix)){
                    resStr+= suffix;
                }
            }
            return  resStr;
        }
        return "";
    }
}
